package com.example.demo.service.impl;

import com.example.demo.common.constant.MessageConstant;
import com.example.demo.common.exception.AccountNotFoundException;
import com.example.demo.common.exception.PasswordErrorException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.entity.Result;
import com.example.demo.pojo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.time.LocalDateTime;

import static com.example.demo.utils.BCryptUtils.encryptPassword;
import static com.example.demo.utils.BCryptUtils.matchesPassword;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public Result register(String username, String password) {
        password = encryptPassword(password);
        LocalDateTime time = LocalDateTime.now();
        userMapper.register(username, password, time);
        return Result.success();
    }

    @Override
    public User login(String username, String password)  {
        User user = userMapper.login(username);
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!matchesPassword(password, user.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        userMapper.is_trial(username);
        return user;
    }

    @Override
    public User getBuyId(Long id) {
        User user = userMapper.getBuyId(id);
        return user;
    }

}
